/*
 * Copyright 2007 Ulf Ochsenfahrt <ulf@ofahrt.de>
 *
 * This file is part of mnemoj, a software transactional memory implementation
 * that is based on Project Darkstar.
 *
 * mnemoj is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation and
 * distributed hereunder to you.
 *
 * Project Darkstar Server is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.ofahrt.mnemoj.impl;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.sun.sgs.app.ObjectNotFoundException;
import com.sun.sgs.app.Task;

final class ManagedTask implements Task, Comparable<ManagedTask>
{

private final Lock lock = new ReentrantLock();
private final long time;
private final long id;
private final Long managedId;
private final byte[] serializedForm;

ManagedTask(long time, long id, byte[] serializedForm)
{
	this.time = time;
	this.id = id;
	this.managedId = null;
	this.serializedForm = serializedForm;
}

ManagedTask(long time, long id, Long managedId)
{
	this.time = time;
	this.id = id;
	this.managedId = managedId;
	this.serializedForm = null;
}

public Lock getLock()
{ return lock; }

public long getTime()
{ return time; }

public long getId()
{ return id; }

@Override
public int compareTo(ManagedTask o)
{
	if (time < o.time) return -1;
	if (time > o.time) return 1;
	if (id < o.id) return -1;
	if (id > o.id) return 1;
	return 0;
}

@Override
public int hashCode()
{ return (int) (time+(time >>> 32)+id+(id >>> 32)); }

@Override
public boolean equals(Object o)
{
	if (o == this) return true;
	if (!(o instanceof ManagedTask)) return false;
	ManagedTask h = (ManagedTask) o;
	return (h.time == time) && (h.id == id);
}

private Task getCopy()
{
	if (serializedForm == null)
		throw new ObjectNotFoundException();
	return (Task) SerializationHelper.deserialize(serializedForm);
}

@Override
public void run()
{
	Task task;
	if (managedId != null)
		task = (Task) AppContextDispatcher.getTaskTransaction().get(managedId);
	else
		task = getCopy();
	task.run();
}

}
